package com.book.bookmanager.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.bookmanager.mapper.RoleMenuMapper;
import com.book.bookmanager.mapper.roleMapper;
import com.book.bookmanager.pojo.Role;
import com.book.bookmanager.pojo.RoleMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class roleServiceImpl extends ServiceImpl<roleMapper, Role> implements roleService {
    @Autowired
    private roleMapper rm;
    @Autowired
    private RoleMenuMapper roleMenuMapper;


    @Override
    public List<Role> queryAll() {
        return rm.selectAll();
    }

    @Override
    public void add(Role role) {
        rm.add(role);
    }


    @Override
    public void removeByRoleId(Integer id) {
        rm.remove(id);
    }

    @Override
    public void addRole(Role role) {
        //写入角色表

        this.baseMapper.insert(role);
        //写入角色-菜单表
        Integer a = role.getRole_id();

            addMenuIdList(role);


    }

    @Override
    public Role queryByRoleId(Integer role_id) {
        Role role = this.baseMapper.queryByRoleId(role_id);

        List<Integer> menuIdList = roleMenuMapper.getMenuIdListByRoleId(role_id);
        role.setMenuIdList(menuIdList);
        return role;

    }

    @Override
    public void updateRole(Role role) {
        //修改role表
        this.baseMapper.updateByRoleId(role);

        //删除roleMenu表菜单栏
        LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleMenu::getRole_id,role.getRole_id());
        roleMenuMapper.delete(wrapper);

        //新增roleMenu表菜单栏
        addMenuIdList(role);
    }
    private void addMenuIdList(Role role){
        if (null != role.getMenuIdList()) {
            //新增roleMenu表菜单栏
            for (Integer menuId : role.getMenuIdList()) {
                roleMenuMapper.insertRoleMenu(new RoleMenu(null, role.getRole_id(), menuId));

            }
        }
    }
}
